package admin

import (
	"net/http"
	"shop/internal/models"
	"shop/internal/service/new_cate_service"
	"shop/pkg/app"
	"shop/pkg/constant"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

// 新分类api
type NewCategoryController struct {
}

// @Title 新分类列表
// @Description 新分类列表
// @Success 200 {object} app.Response
// @router / [get]
func (e *NewCategoryController) GetAll(c *gin.Context) {
	var (
		appG = app.Gin{C: c}
	)
	name := c.DefaultQuery("name", "")
	enabled := com.StrTo(c.DefaultQuery("enabled", "-1")).MustInt()
	newCareService := new_cate_service.NewCate{Name: name, Enabled: enabled}
	vo := newCareService.GetNewCateAll()
	appG.Response(http.StatusOK, constant.SUCCESS, vo)
}

// 添加新闻分类
func (e *NewCategoryController) Post(c *gin.Context) {
	var (
		model models.NewCategory
		appG  = app.Gin{C: c}
	)
	httpCode, errCode := app.BindAndValid(c, &model)
	if errCode != constant.SUCCESS {
		appG.Response(httpCode, errCode, nil)
		return
	}
	newCateService := new_cate_service.NewCate{
		M: &model,
	}

	if err := newCateService.Insert(); err != nil {
		appG.Response(http.StatusInternalServerError, constant.FAIL_ADD_DATA, nil)
		return
	}
	appG.Response(http.StatusOK, constant.SUCCESS, nil)
}

// @Title 修改分类
// @Description 修改分类
// @Success 200 {object} app.Response
func (e *NewCategoryController) Put(c *gin.Context) {
	var (
		model models.NewCategory
		appG  = app.Gin{C: c}
	)
	httpCode, errCode := app.BindAndValid(c, &model)
	if errCode != constant.SUCCESS {
		appG.Response(httpCode, errCode, nil)
		return
	}
	newCateService := new_cate_service.NewCate{
		M: &model,
	}

	if err := newCateService.Save(); err != nil {
		appG.Response(http.StatusInternalServerError, constant.FAIL_ADD_DATA, nil)
		return
	}
	appG.Response(http.StatusOK, constant.SUCCESS, nil)
}

// @Title 删除分类
// @Description 删除分类
// @Success 200 {object} app.Response
func (e *NewCategoryController) Del(c *gin.Context) {
	var (
		ids  []int64
		appG = app.Gin{C: c}
	)
	c.BindJSON(&ids)
	newCateService := new_cate_service.NewCate{
		Ids: ids,
	}
	if err := newCateService.Delete(); err != nil {
		appG.Response(http.StatusInternalServerError, constant.FAIL_ADD_DATA, nil)
		return
	}
	appG.Response(http.StatusOK, constant.SUCCESS, nil)

}
